<!--
  <div>
    带压缩的上传
    <upload-image v-model="imageUrl" :fileSize="512" />
    已上传文件 {{ imageUrl }}
  </div>
-->

<template>
  <div>
    <el-upload
      class="image-uploader"
      :action="`${path}/base/upload`"
      :show-file-list="false"
      :on-success="handleImageSuccess"
      :before-upload="beforeImageUpload"
      :multiple="false"
    >
      <div v-if="imageUrl" class="image-wrapper">
        <img :src="imageUrl" class="image">

        <div class="overlay">
          <i class="el-icon-delete" @click.stop="$emit('change', '')" />
          <i class="el-icon-view" @click.stop="dialogVisible = true" />
        </div>
      </div>
      <i v-else class="el-icon-plus image-uploader-icon" />
    </el-upload>

    <el-dialog
      :visible.sync="dialogVisible"
    >
      <img :src="imageUrl" width="100%">
    </el-dialog>
  </div>
</template>

<script>
const path = process.env.VUE_APP_BASE_API
import { mapGetters } from 'vuex'
import ImageCompress from '@/utils/image'
export default {
  name: 'UploadImage',
  model: {
    prop: 'imageUrl',
    event: 'change'
  },
  props: {
    imageUrl: {
      type: String,
      default: ''
    },
    fileSize: {
      type: Number,
      default: 2048 // 2M 超出后执行压缩
    },
    maxWH: {
      type: Number,
      default: 1920 // 图片长宽上限
    }
  },
  data() {
    return {
      path: path,
      dialogVisible: false
    }
  },
  computed: {
    ...mapGetters('user', ['userInfo', 'token'])
  },
  methods: {
    beforeImageUpload(file) {
      const isRightSize = file.size / 1024 < this.fileSize
      if (!isRightSize) {
        // 压缩
        const compress = new ImageCompress(file, this.fileSize, this.maxWH)
        return compress.compress()
      }
      return isRightSize
    },
    handleImageSuccess(res) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      const { data } = res
      if (data.file) {
        this.$emit('change', '/' + data.file.url)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.image-uploader {
  border: 1px dashed #d9d9d9;
  width: 84px;
  height: 84px;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border-color: #409eff;

  .image-wrapper {
    img {
      object-fit: cover;
    }

    &:hover {
      .overlay {
        display: flex;
      }
    }
  }
}
.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 84px;
  height: 84px;
  line-height: 84px;
  text-align: center;
}
.image {
  width: 84px;
  height: 84px;
  display: block;
}

.overlay {
  display: none;
  background: rgba(0, 0, 0, 0.65);
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  color: white;
  align-items: center;
  justify-content: space-around;
  padding: 0 2px;
  font-size: 20px;

}
</style>
